<script lang="ts" setup>
import { reactive, ref, shallowRef, onMounted, onActivated, h, createApp } from 'vue'
import { useMap } from '@/hooks/useMap'
import { useActivated } from '@/hooks/useActivated'
import { useRoute } from 'vue-router'
import SearchPlace from '@/components/map/SearchPlace.vue'
import CabinetImg from '@/assets/map/cabinetLocation/cabinet.png'
import { queryBoxDetail, openDoor } from '@/api/cabinet'
import { queryBoxBoxDetailResponseData } from '@/api/cabinet/types/cabinet'
import { getToken } from '@/utils/cache/cookies'
import { ElMessage } from 'element-plus'
import locationImg from '@/assets/map/bikeLocation/location.png'
import CustomActiveButtonGroup from '@/components/basic/ui-elements/CustomActiveButtonGroup.vue'
import CustomActiveButton from '@/components/basic/ui-elements/CustomActiveButton.vue'
import CabinetInfo from '@/components/dialog/CabinetInfo.vue'
defineOptions({
  name: 'CabinetLocation'
})
const route = useRoute()
const center = reactive({
  longtitude: Number(route.query.longtitude),
  latitude: Number(route.query.latitude),
  boxId: Number(route.query.boxId)
})
const isInit = ref<boolean>(false)
const address = ref<any>('')
const data = ref<queryBoxBoxDetailResponseData | null>(null)
const mapContainer = ref<HTMLDivElement>()
const marker = shallowRef<AMap.Marker>()
const infoWindow = shallowRef<AMap.InfoWindow>()
const { map, auto, initAmap, getAddress, placeSearch } = useMap(mapContainer, [
  center.longtitude,
  center.latitude
])
const doorId = ref<string>('')
/** 地图初始化 */
const init = async () => {
  isInit.value = await initAmap()
  getCabinetInfo()
  handleCoverInit(center)
}
const handleCoverInit = async (params?: any) => {
  if (isInit.value && map.value) {
    map.value.clearMap()
    address.value = await getAddress(params?.longtitude, params?.latitude)
    marker.value = new AMap.Marker({
      position: new AMap.LngLat(center.longtitude, center.latitude),
      map: map.value,
      icon: new AMap.Icon({
        image: CabinetImg,
        imageSize: new AMap.Size(59, 63),
        size: new AMap.Size(59, 63)
      }),
      offset: new AMap.Pixel(-30, -63)
    })
    infoWindow.value = new AMap.InfoWindow({
      position: new AMap.LngLat(center.longtitude, center.latitude),
      isCustom: true,
      autoMove: true,
      offset: new AMap.Pixel(0, -60),
      content: createContent(
        data.value?.boxCode ?? '',
        address.value,
        data.value?.battery60VCount ?? '0',
        data.value?.battery48VCount ?? '0'
      )
    })
    infoWindow.value.open(map.value, [center.longtitude, center.latitude])
    marker.value.on('click', () => {
      if (infoWindow.value?.getIsOpen()) {
        infoWindow.value.close()
      } else {
        infoWindow.value?.open(map.value!, [center.longtitude, center.latitude])
      }
    })
    const mapContainer = document.getElementById('map-container')
    mapContainer?.addEventListener('click', handleInfoWindowClick)
  }
}

const getCabinetInfo = async () => {
  try {
    const res = await queryBoxDetail({
      boxId: center.boxId,
      token: getToken() ?? ''
    })
    if (res.statusCode === '0') {
      data.value = res.data
      handleCoverInit(center)
    }
  } catch (error) {
    ElMessage.error({
      plain: true,
      message: '获取电柜信息失败'
    })
    console.error(error)
  }
}
const createContent = (
  boxCode: string,
  address: string,
  count60: string,
  count48: string
): HTMLElement => {
  const container = document.createElement('div')
  // 创建 Vue 应用
  const app = createApp({
    render() {
      return h('div', { class: 'cabinet-position-infowindow' }, [
        h('div', { class: 'cabinet-position-infowindow__title' }, [
          h('span', { class: 'cabinet-position-infowindow__bikeId' }, `电柜编号: ${boxCode}`),
          h('span', { class: 'cabinet-position-infowindow__x' }, 'X')
        ]),
        h('div', { class: 'cabinet-position-infowindow__container' }, [
          h('img', { src: locationImg, alt: 'Location' }), // 替换为实际图片路径
          h('div', { class: 'cabinet-position-infowindow__content' }, [
            h('span', { class: 'cabinet-position-infowindow__address' }, [
              h('span', address),
              h('span', { class: 'is-reference', 'data-address': address }, '复制')
            ]),
            h('div', { class: 'cabinet-position-infowindow__battery-number' }, [
              h('span', `当前可用: ${count60 + count48} 块`),
              h('span', `48V 可用: ${count48} 块`),
              h('span', `60V 可用: ${count60} 块`)
            ]),
            h(
              CustomActiveButtonGroup,
              {
                modelValue: doorId.value,
                class: 'cabinet-position-infowindow__door-button-group',
                'onUpdate:modelValue': (value) => (doorId.value = value as string)
              },
              {
                default: () =>
                  Array.from({ length: 9 }, (_, item) =>
                    h(
                      CustomActiveButton,
                      {
                        class: ['door-button', !isCanUse(item + 1) ? 'no-can-use' : ''],
                        activeValue: (item + 2).toString(),
                        inactiveValue: '',
                        key: item
                      },
                      () => (item + 2).toString()
                    )
                  )
              }
            )
          ])
        ]),
        h('div', { class: 'cabinet-position-infowindow__button' }, [
          h('button', { class: 'open-door-button' }, '点击开仓'),
          h('button', { class: 'show-detail' }, '查看详情')
        ])
      ])
    }
  })

  // 挂载 Vue 应用到 container
  app.mount(container)

  return container
}
const handleOpenDoor = () => {
  if (!doorId.value) {
    ElMessage.warning('无法获取到开启的仓门号')
    return
  }
  openDoor({
    doorId: doorId.value,
    boxId: data.value?.boxId ? data.value?.boxId : 0,
    token: getToken() ?? ''
  }).then((res) => {
    if (res.statusCode === '0') {
      ElMessage.success(res.data)
    } else {
      ElMessage.error(res.data)
    }
  })
}
const isCanUse = (doorNumber: number) => {
  if (data.value?.validDoor.includes(doorNumber)) {
    return true
  } else {
    return false
  }
}
/** 给地图添加点击事件 用于刷新 */
const handleInfoWindowClick = (event: any) => {
  // 检查是否点击了 "开启舱门" 按钮
  if (event.target.className.includes('open-door-button')) {
    handleOpenDoor()
  }
  /** 检查是否点击了 "查看详情" 按钮  */
  if (event.target.className.includes('show-detail')) {
    showCabinetInfo(Number(route.query.boxId))
  }
}
const cabinetInfoRef = ref<InstanceType<typeof CabinetInfo> | null>(null)
const showCabinetInfo = (boxId: number) => {
  cabinetInfoRef.value?.setId(boxId)
  cabinetInfoRef.value?.open()
}
onMounted(() => {
  init()
})
/** 处理是否缓存 */
useActivated(
  center,
  { center },
  [
    { key: 'longtitude', path: 'center.longtitude' },
    { key: 'latitude', path: 'center.latitude' }
  ],
  handleCoverInit,
  ['type']
)
onActivated(() => {
  center.longtitude = Number(route.query.longtitude)
  center.latitude = Number(route.query.latitude)
})
</script>

<template>
  <div class="xy-map-container">
    <div ref="mapContainer" id="map-container">
      <search-place :auto="auto" :map="map!" :place-search="placeSearch" />
      <cabinet-info ref="cabinetInfoRef" />
    </div>
  </div>
</template>

<style scoped lang="scss">
:deep(.cabinet-position-infowindow) {
  z-index: 999;
  position: relative;
  display: flex;
  flex-direction: column;
  background: var(--xy-white-color);
  box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
  border-radius: 8px;
  width: auto;
  .cabinet-position-infowindow__title {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    padding: 8px 12px 0 12px;
  }
  .cabinet-position-infowindow__bikeId {
    color: var(--xy-normal-text-color);
    font-size: 16px;
    line-height: 1;
    font-weight: 500;
  }
  .cabinet-position-infowindow__x {
    color: var(--xy-grey-text-color);
  }
  .cabinet-position-infowindow__container {
    padding: 8px 12px 0 12px;
    display: flex;
    img {
      width: 12px;
      height: 12px;
      margin-right: 10px;
    }
  }
  .cabinet-position-infowindow__button {
    width: 100%;
    display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr;
    button {
      outline: none;
      border: none;
      cursor: pointer;
      color: var(--xy-primary-color);
      background: var(--xy-white-color);
      padding: 10px 0;
    }
  }
  .cabinet-position-infowindow__content {
    display: flex;
    flex-direction: column;
  }
  .cabinet-position-infowindow__address {
    font-size: 12px;
    color: var(--xy-normal-text-color);
    line-height: 14px;
  }
  .cabinet-position-infowindow__battery-number {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 12px;
    color: var(--xy-normal-text-color);
    line-height: 14px;
    margin-top: 10px;
  }
  .cabinet-position-infowindow__door-button-group {
    margin-top: 10px;
  }
  .door-button {
    width: 24px;
    height: 24px;
    padding: 0;
  }
  .no-can-use {
    background: #f0f2f5;
    color: var(--xy-light-color);
  }
}
</style>
